package c_leetcode.a_17_number_combinations;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DFS - 回溯
 * 时间复杂度    (3^m * 4^n)
 * 空间复杂度
 *
 * @author He Kuntao
 * @since 2025/3/20 12:48
 */
public class Backtrack {
    public static void main(String[] args) {
        List<String> strings = new Backtrack().letterCombinations("23");
        System.out.println(strings);
    }

    public List<String> letterCombinations(String digits) {
        ArrayList<String> combinations = new ArrayList<>();
        if (digits.isEmpty()) {
            return combinations;
        }
        Map<Character, String> phoneMap = initMap();
        backtrack(combinations, phoneMap, digits, 0 , new StringBuffer());
        return combinations;
    }

    private void backtrack(ArrayList<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer sb) {
        if (index == digits.length()) {
            combinations.add(sb.toString());
        }else {
            char[] chars = phoneMap.get(digits.charAt(index)).toCharArray();
            for (char c : chars) {
                sb.append(c);
                backtrack(combinations, phoneMap, digits, index + 1, sb);
                sb.deleteCharAt(index);
            }
        }
    }

    private Map<Character, String> initMap() {
        Map<Character, String> result = new HashMap<>();
        result.put('2', "abc");
        result.put('3', "def");
        result.put('4', "ghi");
        result.put('5', "jkl");
        result.put('6', "mno");
        result.put('7', "pqrs");
        result.put('8', "tuv");
        result.put('9', "wxyz");
        return result;
    }
}
